// pages/release-bidding/release-bidding.js
import { Bidding } from '../../models/bidding'
import { check } from '../../util/identityCheck'
import { Publish } from '../../models/other'
import areaList from '../../util/area'
const publishModel = new Publish()
const biddingModel = new Bidding()
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'
import UploadImg from '../../util/uploadImg'
const uploadImg = new UploadImg()
import { RedPacket } from '../../models/redpacket'
let packetModel = new RedPacket()
function getShareId() {
  const shareId = wx.getStorageSync('otherId')
  if (shareId && shareId != 'undefined') {
    // 注意 这里是字符串类型的undefined 好奇我为什么没封装一下？因为我真的很忙
    return shareId
  } else {
    return ''
  }
}
Page({
  data: {
    totalMoney: 0,
    showRedPacketDialog: false,
    id: null,
    areaList,
    showPopup: {
      location: false,
      projects: false
    },
    Bidding: {
      shareUserId: '',
      avatar: '',
      biddingProjectName: '',
      title: '',
      contactName: '',
      contactPhone: '',
      shopName: '',
      shopEnvironment: '',
      shopEnvironmentList: [],
      location: '',
      address: ''
    }
  },

  onShow() {
    const shareUserId = getShareId()
    setTimeout(() => {
      this.setData({
        'Bidding.shareUserId': shareUserId
      })
    }, 1000)
    if (!check()) return
  },

  onLoad(options) {
    this.setData({
      id: options.id
    })
    if (+options.id) {
      this.getDetail()
    } else {
      this.getDraft()
      this.setData({
        showRedPacketDialog: true
      })
    }
  },

  getDetail() {
    biddingModel.detail(
      {
        id: this.data.id
      },
      (res) => {
        wx.hideLoading()
        this.setData({
          Bidding: res
        })
        if (res.auditStatus == 2) {
          Dialog.alert({
            title: '审核未通过',
            message: `未通过原因：${res.remark} \n 请重新修改并提交审核。`
          }).then(() => {
            // on close
          })
        }
      }
    )
  },

  publish() {
    let Bidding = this.data.Bidding
    if (!Bidding.avatar) {
      wx.showToast({
        title: '请上传封面招聘',
        icon: 'none'
      })
      return
    }
    if (!Bidding.title) {
      wx.showToast({
        title: '请填写标题',
        icon: 'none'
      })
      return
    }
    if (!Bidding.shopName) {
      wx.showToast({
        title: '请填写店铺名称',
        icon: 'none'
      })
      return
    }
    if (!Bidding.biddingProjectName) {
      wx.showToast({
        title: '请选择招标项目',
        icon: 'none'
      })
      return
    }
    if (!Bidding.location) {
      wx.showToast({
        title: '请选择所在区域',
        icon: 'none'
      })
      return
    }
    if (!Bidding.address) {
      wx.showToast({
        title: '请填写详细地址',
        icon: 'none'
      })
      return
    }
    if (!Bidding.shopArea) {
      wx.showToast({
        title: '请填写店铺面积',
        icon: 'none'
      })
      return
    }
    if (!Bidding.contactName) {
      wx.showToast({
        title: '请填写联系人',
        icon: 'none'
      })
      return
    }
    if (/^[0-9]*$/.test(Bidding.contactName)) {
      wx.showToast({
        title: '联系人不可以是数字',
        icon: 'none'
      })
      return
    }
    if (!Bidding.contactPhone) {
      wx.showToast({
        title: '请填写联系电话',
        icon: 'none'
      })
      return
    }
    if (!Bidding.shopEnvironmentList.length) {
      wx.showToast({
        title: '请上传店铺照片',
        icon: 'none'
      })
      return
    }
    if (Bidding.contactPhone.includes('*')) {
      delete Bidding.contactPhone
    }
    this.removeDraft()
    biddingModel.publish(Bidding, (res) => {
      if (res.getPacket) {
        // 第一次发布
        this.tip('发布成功！', 'publish')
      } else {
        this.tip('发布成功！')
      }
    })
  },

  update() {
    let Bidding = this.data.Bidding
    Dialog.confirm({
      message: '更新后需再次审核\n 是否确认更新？'
    }).then(() => {
      if (Bidding.contactPhone.includes('*')) {
        delete Bidding.contactPhone
      }
      biddingModel.update(Bidding, (res) => {
        this.tip('更新成功！')
      })
    })
  },

  confirmDialogTip() {
    wx.navigateBack({
      delta: 1
    })
  },

  onReady() {
    this.init()
  },

  inputChange(evevt) {
    let key = `Bidding.${evevt.currentTarget.dataset.type}`
    this.setData({
      [key]: evevt.detail
    })
  },

  onShowPopup(e) {
    // 打开弹窗
    wx.hideKeyboard()
    const which = e.currentTarget.dataset.key
    const key = `showPopup.${which}`
    this.setData({
      [key]: true
    })
  },

  onClosePopup() {
    // 关闭弹窗
    for (let key in this.data.showPopup) {
      key = `showPopup.${key}`
      this.setData({
        [key]: false
      })
    }
  },

  onBuyWay(e) {
    // 选择转让方式
    this.setData({
      'Bidding.buyWay': e.detail
    })
  },

  onProject(e) {
    // 选择招标项目
    this.setData({
      'Bidding.biddingProjectName': e.detail
    })
  },

  chooseLocation() {
    let that = this
    wx.chooseLocation({
      success(res) {
        that.setData({
          'Bidding.address': res.name
        })
      }
    })
  },

  onAreaConfirm(e) {
    const location = e.detail.values
    this.setData({
      'Bidding.location':
        location[0].name + location[1].name + location[2].name,
      'showPopup.location': false
    })
  },

  onAreaCancel(e) {
    this.setData({
      'showPopup.location': false
    })
  },

  getBuyWay() {
    // 获取转让方式
    publishModel.getPublicTypes(
      {
        tagKey: '购入方式',
        type: 1
      },
      (res) => {
        this.setData({
          buyWayList: res
        })
      }
    )
  },

  getProjects() {
    biddingModel.projects(
      {
        type: 2
      },
      (res) => {
        this.setData({
          projects: res
        })
      }
    )
  },

  uploadCover() {
    uploadImg.chooseImg(1, (imgUrl) => {
      this.setData({
        'Bidding.avatar': imgUrl
      })
    })
  },

  chooseImage() {
    uploadImg.chooseImg(5, (res) => {
      let imgList = this.data.Bidding.shopEnvironmentList
      imgList.push(res)
      this.setData({
        'Bidding.shopEnvironmentList': imgList,
        'Bidding.shopEnvironment': imgList.join(',')
      })
    })
  },

  removeImg(e) {
    const index = e.currentTarget.dataset.index
    let imgList = this.data.Bidding.shopEnvironmentList
    imgList.splice(index, 1)
    this.setData({
      'Bidding.shopEnvironmentList': imgList,
      'Bidding.shopEnvironment': imgList.join(',')
    })
  },

  tip(title, type) {
    if (type === 'publish') {
      Dialog.alert({
        message: `恭喜你${this.data.totalMoney}元红包已到账 \n 信息审核通过后，红包即可提现！`,
        confirmButtonText: '邀请拿红包',
        cancelButtonText: '查看红包',
        showCancelButton: true,
        cancelButtonColor: '#23DEAF',
        confirmButtonOpenType: 'share'
      })
        .then(() => {
          wx.requestSubscribeMessage({
            tmplIds: [
              '-DHKrW9DRvbg3sEoVRYtcRxRyr-kYzyTN-9BNCY89rI',
              'b7FIjt52cUMvTClpMJKJLe8lzi4rnQsWlUc7D5VYGoA',
              'PbmE0p7hgtUXlZcUEgR_qBcP3tMhbe1-_wKNw7CkoZY'
            ],
            complete(res) {
              wx.navigateBack()
            }
          })
        })
        .catch(() => {
          wx.requestSubscribeMessage({
            tmplIds: [
              '-DHKrW9DRvbg3sEoVRYtcRxRyr-kYzyTN-9BNCY89rI',
              'b7FIjt52cUMvTClpMJKJLe8lzi4rnQsWlUc7D5VYGoA',
              'PbmE0p7hgtUXlZcUEgR_qBcP3tMhbe1-_wKNw7CkoZY'
            ],
            complete(res) {
              wx.redirectTo({
                url: `/packageA/pages/my-redpacket/my-redpacket`
              })
            }
          })
        })
    } else {
      Dialog.alert({
        title,
        message: '平台将在24小时内完成审核，请耐心等待！'
      }).then(() => {
        wx.requestSubscribeMessage({
          tmplIds: [
            '-DHKrW9DRvbg3sEoVRYtcRxRyr-kYzyTN-9BNCY89rI',
            'b7FIjt52cUMvTClpMJKJLe8lzi4rnQsWlUc7D5VYGoA',
            'PbmE0p7hgtUXlZcUEgR_qBcP3tMhbe1-_wKNw7CkoZY'
          ],
          complete(res) {
            wx.navigateBack()
          }
        })
      })
    }
  },

  delete() {
    Dialog.confirm({
      message: '删除后信息将不再展示，且不可恢复！\n 是否确认删除？'
    }).then(() => {
      biddingModel.delete(
        {
          id: this.data.id
        },
        (res) => {
          wx.showToast({
            title: '删除成功',
            icon: 'none'
          })
          wx.navigateBack({
            delta: 1
          })
        }
      )
    })
  },

  saveDraft() {
    wx.setStorageSync('biddingData', this.data.Bidding)
    wx.showToast({
      title: '草稿保存成功！'
    })
  },

  getDraft() {
    const Bidding = wx.getStorageSync('biddingData') || this.data.Bidding
    this.setData({
      Bidding
    })
  },

  removeDraft() {
    wx.removeStorageSync('biddingData')
  },

  touchmove() {
    // 空函数 防止滚动
  },

  getPacketSize() {
    packetModel.getPacketSize((res) => {
      res.forEach((item) => {
        if (item.modeName == '招标') {
          this.setData({
            totalMoney: item.totalMoney
          })
        }
      })
    })
  },

  closeDialog() {
    this.setData({
      showRedPacketDialog: false
    })
  },

  init() {
    this.getProjects()
    this.getPacketSize()
  }
})
